package TCPConnector

import (
	"gitee.com/csingo/cHelper"
	"log"
	"net"
	"os"
	"strings"
	"time"
)

type ConnectCommand struct {
	Token string
	T     int64
	Count int64
}

func (i *ConnectCommand) CommandName() (app, name string) {
	return "TCPConnector", "ConnectCommand"
}

func (i *ConnectCommand) Dial(address string) {
	i.T = time.Now().Unix()
	t := time.NewTicker(interval * time.Second)
	stop := make(chan struct{})
	exit := make(chan struct{})
	defer func() {
		t.Stop()
		stop <- struct{}{}
		i.Count++
		if i.Count >= reconnect {
			log.Printf("%s，终止程序", recover())
			os.Exit(0)
		}
		log.Printf("%s，网络重连", recover())
	}()

	go func(ticker *time.Ticker, signal, e chan struct{}, instance *ConnectCommand) {
		for {
			select {
			case <-ticker.C:
				now := time.Now().Unix()
				if instance.T != 0 && now-instance.T > timeout {
					log.Println("网络异常(2)，网络重连")
					instance.T = time.Now().Unix()
					e <- struct{}{}
				}
			case <-signal:
				return
			}
		}
	}(t, stop, exit, i)

	conn, err := net.Dial("tcp", address)
	if err != nil {
		panic("网络异常(3)")
	}
	defer conn.Close()

	for {
		select {
		case <-exit:
			panic("网络异常(7)")
		default:
			i.Token = cHelper.RandomStr(length, cHelper.RandomType_LowerChar)

			_, err = conn.Write([]byte(i.Token))
			if err != nil {
				panic("网络异常(4)")
			}

			i.T = time.Now().Unix()

			buffer := make([]byte, buf)
			_, err = conn.Read(buffer)
			if err != nil {
				panic("网络异常(5)")
			}

			var body []byte
			for _, item := range buffer {
				if item != 0 {
					body = append(body, item-offset)
				}
			}

			if !cHelper.PasswordVerify(strings.ToUpper(i.Token), string(body)) {
				panic("网络异常(6)")
			}

			i.T = time.Now().Unix()
			i.Count = 0
			time.Sleep(sleep * time.Second)
		}
	}

}
